package cn.three.learn.server;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @Description: 作用描述
 * @Author: hmm
 * @CreateDate: 2019/7/26$ 21:04$
 * @UpdateUser: hmm
 * @UpdateDate: 2019/7/26$ 21:04$
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@Component
public class NettyServerFilter extends ChannelInitializer<SocketChannel> {
    @Autowired
    private NettyServerHandler nettyServerHandler;

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline ph = ch.pipeline();

        //入参说明: 读超时时间、写超时时间、所有类型的超时时间、时间格式
        ph.addLast(new IdleStateHandler(30, 0, 0, TimeUnit.SECONDS));
        // 解码和编码，应和客户端一致
        // 传输的协议 websocket
        ph.addLast(new HttpResponseEncoder());
        ph.addLast(new HttpRequestDecoder());
        ph.addLast(new HttpObjectAggregator(65536));
        ph.addLast(new WebSocketServerProtocolHandler("/ws"));
        ph.addLast(new NettyServerHandler());

        //业务逻辑实现类
        ph.addLast("nettyServerHandler", nettyServerHandler);
    }
}
